import React, { useEffect, useState, useRef } from 'react'
import {
  Row,
  Col,
  message,
  Skeleton,
  Button,
  Card,
  Divider,
  Modal,
  AutoComplete,
  Typography,
  Popconfirm,
  Tooltip,
  Input,

} from 'antd'
import {
  ModalForm,
  ProFormText,
  ProForm,
  ProFormTextArea,
  ProFormSelect,
  ProFormDependency,
  ProCard,
  CheckCard,
  DrawerForm
} from '@ant-design/pro-components';
import { RightOutlined, ClockCircleOutlined } from '@ant-design/icons';
import DrugModal from './components/DrugModal'
import {
  reqPatientList,
  reqDetal,
  reqUpdate,
  reqPulseUpdate,
  reqPulseDetail,
  reqPulseList,
  reqQuestionTermList,
  reqIllnessList,
  reqIllnessListByGrade
} from '@/services/basicConsultation';

import {
  reqPulseCalibrationList,
  reqTongueCalibrationList,
  reqDiagnosisTermList,
  reqDiagnosisTermListByGrade,
  reqSeniorInquiryList,
  reqSeniorInquiryUpdate,
  reqSymptomList,
  reqSymptomListByGrade
} from '@/services/firstConsultation';


const Consultation: React.FC<any> = ({
  isOpen,
  onCancel,
  user,
  upDataInfo,
  consultationReadonly
}) => {
  const [formObj] = ProForm.useForm()

  const initReadonly =
    user?.seniorInquiry?.inquiryDesciption ||
    user?.seniorInquiry?.diseaseSymptomatic ||
    user?.seniorInquiry?.tyIllnessName ||
    user?.seniorInquiry?.assistantIllnessName;

  const [readonly, setReadonly] = useState(false as boolean);
  const [data, setData] = useState<any>([])
  const [options, setOptions] = useState<any>([])

  const [initialValues, setinitialValues] = useState<any>(null)

  const [inquiryPop, setInquiryPop] = useState(false as boolean)

  function arrayFormatOptions(array: []) {
    if (!Array.isArray(array)) return []
    return array.map((item: any) => ({
      label: item?.name,
      value: item?.name,
    }))
  }

  function arrayFormatOptGroup(array: []) {
    if (!Array.isArray(array)) return []
    return array.map((item: any) => ({
      label: item?.name,
      value: item?.name,
      options: arrayFormatOptions(item?.child)
    }))
  }

  // {
  //   label: 'Manager',
  //   options: [
  //     { label: 'Jack', value: 'jack' },
  //     { label: 'Lucy', value: 'lucy' },
  //   ],
  // },

  async function getTreeList() {
    // const res = await reqSymptomListByGrade({});
    // let parentIds: any = [];
    // res?.data?.map((item: any) => {
    //   if (item?.child) {
    //     item?.child?.map((li: any) => {
    //       parentIds.push(li?.id)
    //     })
    //   }
    // })

    // const res2 = await reqSymptomListByGrade({ parentIds });
    // setOptions(res2?.data)
  }

  async function init() {
    try {
      const res = await reqIllnessList({
        pageNum: 1,
        pageSize: 10,
        illnessType: 2
      })

      // const res2 = await reqSymptomListByGrade({})
      // setOptions(res2?.data)
      // console.log('res2 :>> ', res2?.data);
      // 空的方法？？？
      // await getTreeList()

      console.log('病种病名列表信息 :>> ', res?.data);
      if (res?.resultCode == '00000000') {
        setData(res?.data?.result)
      } else {
        message.error(`病种病名列表信息出错！${res?.message}`)
      }
    } catch (error: any) {
      message.error('病种病名列表信息出错！', error)
      console.log('病种病名列表信息出错！ :>> ', error);
    }
  }


  useEffect(() => {
    if (user?.id) {
      init()
      // console.log('object :>> ', {
      //   illnessNameHistory: user?.illnessNameHistory?.split(','),
      //   medicalHistory: user?.medicalHistory
      // });
      setinitialValues({
        inquiryDesciption: user?.seniorInquiry?.inquiryDesciption ?? undefined,
        //diseaseSymptomatic: user?.seniorInquiry?.diseaseSymptomatic ? user?.seniorInquiry?.diseaseSymptomatic?.split(',') : undefined,
        diseaseSymptomatic: user?.seniorInquiry?.diseaseSymptomatic ? user?.seniorInquiry?.diseaseSymptomatic : undefined,
        tyIllnessName: user?.seniorInquiry?.tyIllnessName ?? undefined,
        assistantIllnessName: user?.seniorInquiry?.assistantIllnessName ? user?.seniorInquiry?.assistantIllnessName?.split(',') : undefined,
      })
    }
  }, [user])


  async function handleAdd(values) {
    console.log('输入病史 :>> ', values);
    // const tyIllnessName = values?.tyIllnessName2 ? values?.tyIllnessName2 : values?.tyIllnessName;

    // console.log('输入病史 :>> ', values, {
    //   ...values,
    //   // illnessNameHistory: values?.illnessNameHistory?.join(',')
    //   tyIllnessName,
    //   assistantIllnessName: values?.assistantIllnessName?.join(','),
    //   diseaseSymptomatic: values?.diseaseSymptomatic?.join(','),
    // });
    // return


    try {
      let { assistantIllnessName = '', diseaseSymptomatic = '', tyIllnessName = '' } = values;

      upDataInfo && upDataInfo({
        ...values,
        // illnessNameHistory: values?.illnessNameHistory?.join(',')
        tyIllnessName,
        assistantIllnessName: Array.isArray(assistantIllnessName) ? assistantIllnessName?.join(',') : assistantIllnessName,
        diseaseSymptomatic: Array.isArray(diseaseSymptomatic) ? diseaseSymptomatic?.join(',') : diseaseSymptomatic
      })
      onCancel(false)
    } catch (error) {
      message.info(error?.message)
    }
    // setOpen(false);
    // setOpen2(false);
    // setOpen3(false);

  }

  const [open, setOpen] = useState<boolean>(false);
  const [dataList, setDataList] = useState();//listByGrade
  const [dataListWithCase, setDataListWithCase] = useState();
  const [checkValue, setCheckValue] = useState<string>();

  const [open2, setOpen2] = useState<boolean>(false);
  const [dataList2, setDataList2] = useState();
  const [dataList2WithCase, setDataList2WithCase] = useState();
  const [checkValue2, setCheckValue2] = useState<string>();

  const [open3, setOpen3] = useState<boolean>(false);
  const [dataList3, setDataList3] = useState();
  const [dataList3WithCate, setDataList3WithCate] = useState();
  const [checkValue3, setCheckValue3] = useState<string>();

  const handleSearch = async (value: string) => {
    let params = { pageSize: 50, illnessType: 2 };
    //Object.assign(params,{"name":value?.trim()});
    const res = await reqIllnessListByGrade(params);
    if (res?.resultCode == "00000000") {
      //setDataList(res?.data?.result);
      console.log('res?.data', res?.data);
      setDataListWithCase(res?.data);
    }
  };

  // assistantIllnessName
  const handleSearch2 = async (value: string) => {
    let params = { pageSize: 50, illnessType: 2 };
    Object.assign(params, { "name": value?.trim() });
    const res = await reqIllnessListByGrade(params);
    if (res?.resultCode == "00000000") {
      //setDataList2(res?.data?.result);
      setDataList2WithCase(res?.data);
    }
  };
  const onChangeCheckCard2 = (item: string) => {
    //formObj.setFieldValue("tyOrganizeId",item?.id);
    formObj.setFieldValue("assistantIllnessName", item);
    setOpen2(false)
  }

  let diseaseSymptomaticLocal = "";
  const handleSearch3 = async (value: string) => {
    let params = { pageSize: 50, illnessType: 2 };
    let newDataList: [] = [];
    Object.assign(params, { "name": value?.trim() });
    if (!value.trim()) {
      const cat = await reqSymptomListByGrade({});
      if (cat?.resultCode == "00000000") {
        setDataList3WithCate(cat?.data)
        newDataList = cat?.data;
      }
    } else {
      const res = await reqSymptomList(params);
      if (res?.resultCode == "00000000") {
        setDataList3(res?.data?.result);
        formObj.setFieldValue("diseaseSymptomatic", "");
        diseaseSymptomaticLocal = "";
      }
    }

  };

  const setTheOpen1 = (isShow: boolean) => {
    if (!consultationReadonly) {
      setOpen(isShow);
      handleSearch("");
    }
  }
  const setTheOpen2 = (isShow: boolean) => {
    if (!consultationReadonly) {
      setOpen2(isShow);
      handleSearch2("");
    }
  }
  const setTheOpen3 = async (isShow: boolean) => {
    if (!consultationReadonly) {
      setOpen3(isShow);
      handleSearch3("");
    }
  }

  const setWinOpen3 = () => {
    setOpen3(false);
    if (diseaseSymptomaticLocal) diseaseSymptomaticLocal = diseaseSymptomaticLocal.substring(1);
    formObj.setFieldValue("diseaseSymptomatic", diseaseSymptomaticLocal);
  }
  const onChangeCheckCard3 = (item: any) => {
    diseaseSymptomaticLocal = "";
    item?.map((it) => {
      diseaseSymptomaticLocal += "," + it;
    })
  }

  return (
    <>
      <DrawerForm
        width={'60vw'}
        layout='vertical'
        style={{ padding: '26px', zIndex: '-1' }}
        visible={isOpen}
        onVisibleChange={(visible) => onCancel(visible)}
        form={formObj}
        readonly={readonly}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => console.log('Cancelled'),
        }}
        // labelCol={{ span: 2 }}
        // submitter={{
        //   // 完全自定义整个区域
        //   render: (props, doms) => {
        //     console.log(props);
        //     return (
        //       readonly ? [] :
        //         <div className='submitBtn'>
        //           <Button
        //             type='primary'
        //             key="submit"
        //             onClick={() => props.form?.submit?.()}
        //           >
        //             保存
        //           </Button>,
        //           <Button
        //             key="rest"
        //             onClick={() => props.form?.resetFields()}
        //           >
        //             重置
        //           </Button>
        //         </div>
        //     )
        //   },
        // }}

        initialValues={initialValues}
        onFinish={(values): Promise<any> => handleAdd(values)}
      >
        {/* <ProFormDependency
            // labelCol={{ span: 2 }}
            name={['tyIllnessName2']}
            shouldUpdate={(prevValues, curValues) => (
              prevValues.tyIllnessName2 !== curValues.tyIllnessName2
            )}
          >
            {({ tyIllnessName2 }) => {
              return (
                // <ProFormSelect
                //   // style={{ width: 200 }}
                //   placeholder="请选择病症"
                //   label={<div className={styles.label}>病名</div>}
                //   name='tyIllnessName'
                //   disabled={tyIllnessName2}
                //   fieldProps={{
                //     dropdownRender: (menu) => (
                //       <>
                //         {menu}
                //       </>
                //     )
                //   }}
                //   options={arrayFormatOptions(data)}
                // />
                <>
                  <div>

                  </div>

                </>
              );
            }}
          </ProFormDependency> */}


        <ProForm.Group>
          <div onClick={() => setOpen(true)}>
            {/* <ProFormText width={330} allowClear={false} label="病症" /> */}
            <ProForm.Item name="tyIllnessName" label="副病名" style={{ width: '386px' }} >
              <Input suffix={<RightOutlined />} />
            </ProForm.Item>
          </div>
          <ProFormText
            width={386}
            label="其他症状"
            name="tyIllnessName2"
            disabled={(true)}
            placeholder="请输入其他病症"
          />
          {/* <ProFormDependency
              name={['tyIllnessName']}
              shouldUpdate={(prevValues, curValues) => (
                prevValues.tyIllnessName !== curValues.tyIllnessName
              )}
            >
              {({ tyIllnessName }) => {
                return (
                  <ProFormText
                    name="tyIllnessName2"
                    disabled={(tyIllnessName)}
                    placeholder="请输入其他病症"
                  />
                );
              }}
            </ProFormDependency> */}
        </ProForm.Group>
        <div onClick={() => setOpen2(true)}>
          <ProForm.Item name="assistantIllnessName" label="副病名" >
            <Input name="assistantIllnessName" suffix={<RightOutlined />} />
          </ProForm.Item>
          {/* <ProFormText prefix={<ClockCircleOutlined />} /> */}
        </div >
        <div onClick={() => setOpen3(true)}>
          <ProForm.Item name="diseaseSymptomatic" label="已选择症状">
            <Input suffix={<RightOutlined />} />
          </ProForm.Item>
        </div >
        <ProFormTextArea
          width='xl'
          name="inquiryDesciption"
          label='问诊'
          placeholder="请输入问诊"
          help={
            <div style={{ marginTop: 10 }}>
              <div>请填写患病情况，例如:</div>
              <div>起病情况(缓急) 与方式;发作原因与诱因，病情的发展与演变:伴随症状，断、治疗经过(药物、剂量、疗效等);患病以来的一般情况精神状态、食欲</div>
              <div>体重改变、睡眠及大小便等情况等。</div>
            </div>
          }
        />

        {/* 备注 弹款层级问题解决方案  */}
        <DrugModal formRef={formObj} name='tyIllnessName' multiple={false} title='病名选择' isDrugModal={open} list={dataListWithCase} onVisibleChange={setTheOpen1} />
        <DrugModal formRef={formObj} name='assistantIllnessName' multiple={true} title='副病名选择' isDrugModal={open2} list={dataList2WithCase} onVisibleChange={setTheOpen2} />
        <DrugModal formRef={formObj} name='diseaseSymptomatic' multiple={true} title='症状选择' isDrugModal={open3} list={dataList3WithCate} onVisibleChange={setTheOpen3} />
      </DrawerForm>
    </ >
  )
}


export default Consultation;